package com.cslg.questionnaires.controller;

import com.cslg.questionnaires.entity.Student;
import com.cslg.questionnaires.entity.User;
import com.cslg.questionnaires.service.LoginService;
import com.cslg.questionnaires.utils.ServiceMessageBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {
    @Autowired
    private LoginService loginService;

    @GetMapping(value = {"/", "/index", "/login"})
    public ModelAndView login_page() {
        return new ModelAndView("login");
    }

    @PostMapping("/login")
    public ModelAndView login(@RequestParam Map<String, String> map, HttpSession session) {
        String username = map.get("username");
        String password = map.get("password");
        String userId = map.get("userId");
        if (userId.equals("student")) {
            username = username.toUpperCase();
            Map<String, Object> resp = loginService.studentLogin(username, password);
            int code = (int) resp.get("code");
            String msg = (String) resp.get("msg");
            Object data = resp.get("data");
            // 密码用户名正确
            if (code == 200) {
                session.setAttribute("user", data);
                session.setAttribute("userType", "Student");
                return new ModelAndView("redirect:/StudentHome?page=1");
            } else {
                return new ModelAndView("login", resp);
            }
        } else { // 教师管理员
            Map<String, Object> resp = loginService.teacherLogin(username, password);
            int code = (int) resp.get("code");
            Object user = resp.get("data");
            if (code == 200) {
                session.setAttribute("user", user);
                session.setAttribute("userType", "Teacher");
                return new ModelAndView("redirect:/TeacherHome?page=1");
            } else {
                return new ModelAndView("login", resp);
            }
        }
    }
}
